package cn.com.websocket.service.impl;

import cn.com.websocket.enums.YesOrNoEnum;
import cn.com.websocket.handle.SocketHandle;
import cn.com.websocket.mapper.MessageMapper;
import cn.com.websocket.po.Message;
import cn.com.websocket.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>消息确认接收</p>
 * */
@Service("ackMsgService")
public class AckMsgServiceImpl extends AbsMessageStrategy{

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    MessageMapper messageMapper;

    @Override
    public void handleMessage(Session session, Message message) {
        if(StringUtil.isEmpty(message.getId())){
            logger.info("============>缺少必须参数!");
            return;
        }
        // 只能更新 自己未接收的消息（消息已经确认接收了，此时需要更新消息的状态）
        int count = messageMapper.updateMessageReadByTarget(message.getSource(),message.getTarget(),message.getId());
        logger.info("=======>用户已经手动确认接收到未读消息了，消息状态更新: {} 条",count);
        //未读消息递增
        String key = SocketHandle.getOfflineMsgKey(message.getSource(),message.getTarget());
        List<Message> messages = SocketHandle.offlineMessage.get(key);
        if(null!=messages){
            Iterator<Message> iterator =messages.iterator();
            while(iterator.hasNext()){
                Message _msg = iterator.next();
                if(message.getId().equals(_msg.getId())){
                    iterator.remove();
                }
            }
        }
        // 这里是获取历史记录，需要更新历史记录消息的 阅读状态
        List<Message> historyList = SocketHandle.historyMessage.get(SocketHandle.getHistorySourceWithTargetKey(message.getSource(),message.getTarget()));
        if(null==historyList){ return; }
        List<Message> updateHistoryList = historyList.stream().filter(msg->msg.getId().equals(message.getId())).collect(Collectors.toList());
        Iterator<Message> historyIterator = updateHistoryList.iterator();
        while (historyIterator.hasNext()) {
            Message historyMsg = historyIterator.next();
            if(historyMsg.getId().equals(message.getId())){
                historyMsg.setRead(YesOrNoEnum.YES.getKey());
                break;
            }
        }
        System.out.println("---------- >>>> 这样移除消息后，缓存不知道有没有更新成功????");
    }
}
